/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.csource.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.RebuildDocumentDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.csource.manage.dto.CaseSourceDocumentRecordDelDto;
import com.icinfo.cloud.provider.punish.csource.manage.dto.CaseSourceLinkRelateDocumentQueryDto;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceDocumentRecordHisMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecordHis;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceDocumentRecordService;
import com.icinfo.cloud.provider.punish.dataprocessing.model.DataProcessCaseMainInfoDelRecord;
import com.icinfo.cloud.provider.punish.dataprocessing.service.IDataProcessCaseMainInfoDelRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.DocumentRecordModifyDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseStageLinkRelateDocumentVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.DocumentRecordModifyReturnVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述: 案源文书记录表 case_source_document_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年08月15日
 */
@Slf4j
@Service
public class CaseSourceDocumentRecordServiceImpl extends MyBatisServiceSupport implements ICaseSourceDocumentRecordService {

    @Autowired
    private CaseSourceDocumentRecordMapper caseSourceDocumentRecordMapper;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseSourceDocumentRecordHisMapper caseSourceDocumentRecordHisMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private IDataProcessCaseMainInfoDelRecordService mainInfoDelRecordService;
    /**
     * 查询案源文书列表
     * @author liyafeng
     * @date 2022/8/15
      * @param query
     * @return {@link List< CaseStageLinkRelateDocumentVo>}
     */
    @Override
    public List<CaseStageLinkRelateDocumentVo> getCaseStageLinkRelateDocumentInfo(CaseSourceLinkRelateDocumentQueryDto query) {
        List<CaseStageLinkRelateDocumentVo> caseStageLinkRelateDocumentList
                = caseSourceDocumentRecordMapper.selectCaseStageLinkRelateDocumentInfo(query);

        Set<String> set = new HashSet<>();
        Iterator<CaseStageLinkRelateDocumentVo> iterator = caseStageLinkRelateDocumentList.iterator();
        while(iterator.hasNext()){
            CaseStageLinkRelateDocumentVo e =  iterator.next();
            //非草稿状态的文书设置相关状态的名称
            if (!DocumentRecordStatusEnum.DRAFT.getCode().equals(e.getDocumentRecordStatus())) {
                e.setDocumentApprovalStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentApprovalStatus()));
                e.setDocumentSentStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentSentStatus()));
                e.setDocumentSignstampedStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentSignstampedStatus()));
            }
            e.setDocumentRecordStatusName(DocumentRecordStatusEnum.getValueByCode(e.getDocumentRecordStatus()));
            //update
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSeal())) {
                e.setDocumentUrl(e.getDocumentUrlAfterSeal());
            }
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSign())) {
                e.setDocumentUrl(e.getDocumentUrlAfterSign());
            }
            String documentKindCode = e.getDocumentKindCode();
            if(Constant.STRING_KIND_CODE_ZXQKHCJL.equals(documentKindCode)){
                String kindCode = e.getDocumentKindCode();
                String partyId = e.getPartyId();
                String combineInfo = kindCode+"_"+partyId;
                if(set.contains(combineInfo)){
                    iterator.remove();
                } else {
                    set.add(combineInfo);
                }
            }
        }
        return caseStageLinkRelateDocumentList;
    }
    /**
     * 查询案源文书
     * @author liyafeng
     * @date 2022/8/16
      * @param caseSourceId
     * @param documentCatalogCode
     * @param partyId
     * @return {@link CaseSourceDocumentRecord}
     */
    @Override
    public CaseSourceDocumentRecord getCaseDocumentRecord(String caseSourceId, String documentCatalogCode, String partyId) {
        //查询文书记录数据
        Example example = new Example(CaseSourceDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("caseSourceId", caseSourceId).andEqualTo("documentCatalogCode", documentCatalogCode)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        if(!ObjectUtils.isEmpty(partyId)){
            criteria.andEqualTo("partyId", partyId);
        }
        List<CaseSourceDocumentRecord> caseSourceDocumentRecords = caseSourceDocumentRecordMapper.selectByExample(example);
        if (caseSourceDocumentRecords == null || caseSourceDocumentRecords.size() == 0) {
            return null;
        }
        return caseSourceDocumentRecords.get(0);
    }

    @Override
    public int delCaseDocumentRecordInfo(CaseSourceDocumentRecordDelDto delDto) {
        String partyId=delDto.getPartyId();
        String caseSourceId=delDto.getCaseSourceId();

        String documentId=delDto.getDocumentId();
        List<CaseSourceDocumentRecord> caseSourceDocumentRecordList=new ArrayList();
        CaseSourceDocumentRecord caseSourceDocumentRecord = caseSourceDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(caseSourceDocumentRecord)){
            throw new BusinessException("文书不存在");
        }
        caseSourceDocumentRecordList.add(caseSourceDocumentRecord);
        //不为空，则添加历史，删除记录
       int num = deleteAndSaveHis(caseSourceDocumentRecordList);
        caseSourceDocumentRecordMapper.deleteByPrimaryKey(delDto.getDocumentId());

        //查询关联文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseSourceDocumentRecord.getDocumentCatalogCode());
        String relateCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
        if (StringUtils.isNotBlank(relateCode)) {
            String[] relateCodeArr = relateCode.split(",");
            for (String relateCodeStr : relateCodeArr) {
                //todo 删除暂存内容 暂时没有暂存

                //查询文书记录数据
                Example relateExample = new Example(CaseSourceDocumentRecord.class);
                relateExample.createCriteria().andEqualTo("caseSourceId", caseSourceId)
                        .andEqualTo("documentCatalogCode", relateCodeStr)
                        .andEqualTo("partyId", partyId)
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));

                List<CaseSourceDocumentRecord> relateCaseDocumentRecords = caseSourceDocumentRecordMapper.selectByExample(relateExample);
                if (null != relateCaseDocumentRecords && relateCaseDocumentRecords.size() > 0) {
                    //删除当前环节附件
                    num = deleteAndSaveHis(relateCaseDocumentRecords);

                }

            }
        }
        //不予立案审批删除时  删除案件
        if(Constant.KIND_CODE_DT2BYLASPB.equals(configBusiParamDocumentInfo.getDocumentKindCode())){
            CaseMainInfo caseInfo=caseMainInfoMapper.selectByPrimaryKey(delDto.getCaseSourceId());
            DataProcessCaseMainInfoDelRecord dataProcessCaseMainInfoDelRecord = BeanUtil.toBean(caseInfo, DataProcessCaseMainInfoDelRecord.class);
            dataProcessCaseMainInfoDelRecord.setCaseLinkTag("业务删除");
            mainInfoDelRecordService.saveRecord(dataProcessCaseMainInfoDelRecord);
            caseMainInfoMapper.deleteByPrimaryKey(delDto.getCaseSourceId());
        }
        return num;
    }

    /**
     * 获取文书记录列表
     *
     * @param caseSourceId 案源唯一标识
     * @param catalogCodeList 文书目录编码列表
     * @return
     * @author lilihao
     * @date 2023/2/7 15:10
     */
    @Override
    public List<CaseSourceDocumentRecord> getDocumentRecordList(String caseSourceId, List<String> catalogCodeList) {
        Example example = new Example(CaseSourceDocumentRecord.class);
        example.createCriteria().andEqualTo("caseSourceId",caseSourceId)
                .andEqualTo("documentRecordStatus", YesOrNoEnum.YES.getCode())
                .andIn("documentCatalogCode",catalogCodeList);
        List<CaseSourceDocumentRecord> list = caseSourceDocumentRecordMapper.selectByExample(example);
        return list;
    }

    /**
     * 根据id获取文书记录
     * @param id 文书id
     * @return  文书信息
     * @author lilihao
     * @date 2023/2/7 17:17
     */
    @Override
    public CaseSourceDocumentRecord getDocumentRecordById(String id) {
        CaseSourceDocumentRecord caseSourceDocumentRecord = caseSourceDocumentRecordMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(caseSourceDocumentRecord)) {
            throw new BusinessException("未匹配到文书记录");
        }
        return caseSourceDocumentRecord;
    }

    /**
     * 修改文书内容/链接
     * @param id 文书id
     * @param documentContent 文书内容
     * @param documentUrl 文书链接
     * @return
     * @author lilihao
     * @date 2023/2/7 19:18
     */
    @Override
    public int modifyDocumentContent(String id, String documentContent, String documentUrl) {
        CaseSourceDocumentRecord sourceDocumentRecord1 = caseSourceDocumentRecordMapper.selectByPrimaryKey(id);

        CaseSourceDocumentRecord sourceDocumentRecord = new CaseSourceDocumentRecord();
        sourceDocumentRecord.setId(id);
        sourceDocumentRecord.setDocumentContent(documentContent);
        sourceDocumentRecord.setDocumentUrl(documentUrl);
        if (StrUtil.isNotBlank(sourceDocumentRecord1.getDocumentUrlAfterSeal())){
            sourceDocumentRecord.setDocumentUrlAfterSeal(documentUrl);
        }else {
            sourceDocumentRecord.setDocumentUrl(documentUrl);
        }
        return caseSourceDocumentRecordMapper.updateByPrimaryKeySelective(sourceDocumentRecord);
    }

    /**
     * 删除并添加历史
     *
     * @param
     * @return {@link int}
     * @author liyafeng
     * @date 2022/3/11
     */
    private int deleteAndSaveHis(List<CaseSourceDocumentRecord>  caseSourceDocumentRecords) {
        int num = 0;
        //不为空，则添加历史，删除记录
        for (CaseSourceDocumentRecord caseSourceDocumentRecord : caseSourceDocumentRecords) {
            //已审批完成的文书不删除
            if (!caseSourceDocumentRecord.getDocumentApprovalStatus().equals(DocumentStatusEnum.CHECK_END.getCode())){
                //添加历史
                CaseSourceDocumentRecordHis caseDocumentRecordHis = new CaseSourceDocumentRecordHis();
                BeanUtils.copyProperties(caseSourceDocumentRecord, caseDocumentRecordHis);
                caseDocumentRecordHis.setId(StringUtils.uuid());
                caseDocumentRecordHis.setRecordId(caseSourceDocumentRecord.getId());
                caseDocumentRecordHis.setOp("delete");
                caseDocumentRecordHis.setHisCreateTime(new Date());
                caseSourceDocumentRecordHisMapper.insert(caseDocumentRecordHis);
                //删除文书记录表
                num = caseSourceDocumentRecordMapper.deleteByPrimaryKey(caseSourceDocumentRecord.getId());
            }
        }
        return num;
    }

    /**
     * 根据案源编码获取案源id
     * @param  documentNumber 案源文书编码
     * @return  案源id
     * @author lilihao
     * @date 2023/3/8 20:24
     */
    @Override
    public String getCaseSourceIdByDocumentNumber(String documentNumber) {
        Example example = new Example(CaseSourceDocumentRecord.class);
        example.createCriteria().andEqualTo("documentNumber",documentNumber);
        List<CaseSourceDocumentRecord> list = caseSourceDocumentRecordMapper.selectByExample(example);
        return CollectionUtil.isNotEmpty(list)?list.get(0).getCaseSourceId():"";
    }
    /**
     * 【V1.11.2】描述： 案源文书修改
     *
     * @author: zhengqiang
     * @date: 2023/3/17
     * @param: saveDto
     * @return {@link DocumentRecordModifyReturnVo}
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DocumentRecordModifyReturnVo modifyCaseSourceDocumentRecord(DocumentRecordModifyDto saveDto) {
        CustomCheckParamUtil.doCheck(saveDto);
        String originalDocumentId = saveDto.getDocumentId();
        String caseId = saveDto.getCaseId();
        CaseSourceDocumentRecord caseSourceDocumentRecord = caseSourceDocumentRecordMapper.selectByPrimaryKey(originalDocumentId);
        if (ObjectUtil.isEmpty(caseSourceDocumentRecord)) {
            throw new BusinessException("文书记录不存在");
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            throw new BusinessException("未登录或登录信息已失效");
        }

        Map<String, Object> dataMap = saveDto.getDataMap();
        // 文书记录修改变更的字段
        JSONObject jsonObject = JSON.parseObject(caseSourceDocumentRecord.getDocumentContent());
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if (ObjectUtil.isNotEmpty(dataMap.get(entry.getKey())) && entry.getValue() != null && !entry.getValue().equals(dataMap.get(entry.getKey()))){
                jsonObject.put(entry.getKey(), dataMap.get(entry.getKey()));
            }
        }
        //原文书内容没有的字段处理
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            if (!jsonObject.containsKey(entry) && ObjectUtil.isNotEmpty(dataMap.get(entry.getKey()))) {
                jsonObject.put(entry.getKey(), dataMap.get(entry.getKey()));
            }
        }

        CaseSourceDocumentRecord modifyDocument = new CaseSourceDocumentRecord();
        BeanUtils.copyProperties(caseSourceDocumentRecord, modifyDocument);

        //案源文书暂没有审批功能 后续可优化
        modifyDocument.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());
        CaseSourceDocumentRecord updateRecord = new CaseSourceDocumentRecord();
        updateRecord.setId(originalDocumentId);
        updateRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.WITHDRAW.getCode());
        caseSourceDocumentRecordMapper.updateByPrimaryKeySelective(updateRecord);

        //新增一条文书记录
        String modifyDocumentId = BaseUtil.createUid();
        modifyDocument.setId(modifyDocumentId);
        modifyDocument.setIsModifyRecord(Constant.STRING_1);
        modifyDocument.setDocumentContent(jsonObject.toString());
        modifyDocument.setCreateUserId(userInfo.getUserId() + "");
        modifyDocument.setCreateUserName(userInfo.getRealName());
        caseSourceDocumentRecordMapper.insertSelective(modifyDocument);
        //3、重新生成文书
        Map<String, Object> paramJson = new HashMap<>(8);

        RebuildDocumentDto dto = new RebuildDocumentDto(modifyDocumentId, "");
        List<RebuildDocumentDto> list = new ArrayList<>();
        list.add(dto);
        paramJson.put("documentInfo", list);
        paramJson.put("documentType", "AY");
        Result<Map<String, Object>> result = stageDocCommonOperateService.rebuildPdf(paramJson);
        log.info("edit document(caseSource),rebuild result :{}", result);
        int num = 0;
        if (ObjectUtil.isNotEmpty(result) && HttpStatus.HTTP_OK == result.getCode()) {
            num = (int) result.getData().get("num");
        }
        DocumentRecordModifyReturnVo vo = new DocumentRecordModifyReturnVo();
        if (num > 0) {
            String documentUrlBeforeModify = ObjectUtil.isNotEmpty(caseSourceDocumentRecord.getDocumentUrlAfterSeal()) ? caseSourceDocumentRecord.getDocumentUrlAfterSeal() : caseSourceDocumentRecord.getDocumentUrl();
            vo.setDocumentUrlBeforeModify(documentUrlBeforeModify);
            vo.setCaseId(caseId);
            vo.setDocumentCatalogCode(saveDto.getDocumentCatalogCode());
            CaseSourceDocumentRecord documentInfoAfterModify = caseSourceDocumentRecordMapper.selectByPrimaryKey(modifyDocumentId);
            String documentUrlAfterModify = ObjectUtil.isNotEmpty(documentInfoAfterModify.getDocumentUrlAfterSeal()) ? documentInfoAfterModify.getDocumentUrlAfterSeal() : documentInfoAfterModify.getDocumentUrl();
            vo.setDocumentUrlAfterModify(documentUrlAfterModify);
            vo.setDocumentIdAfterModify(modifyDocumentId);
            return vo;
        } else {
            throw new BusinessException("修改文书失败,重新生成文书有误");
        }

    }

}
